package com.ciwong.epaper.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.City;
import com.ciwong.epaper.modules.epaper.bean.SchoolDetails;
import com.ciwong.epaper.modules.epaper.bean.SchoolPageBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.utils.Utils;
import com.ciwong.epaper.widget.LetterListView;
import com.ciwong.epaper.widget.wheel.WheelChooser;
import com.ciwong.epaper.widget.wheel.adapter.SchoolListAdapter;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.widget.listview.PullRefreshController;
import com.ciwong.mobilelib.widget.listview.PullRefreshListView;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.UnsupportedEncodingException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * @description:实名登录选择学校页面
 * @author: wyk
 * @time: 2021/8/4 19:07
 */
public class ChooseCitySchoolActivity extends BaseActivity implements PullRefreshController.PullRefreshListener, AbsListView.OnScrollListener, View.OnClickListener {

    private LinearLayout search_school_layout;

    private EditText edt_searching_book_str;

    private ImageView iv_clear_keywords;

    private TextView school_name_text, update_school_text;

    private PullRefreshListView total_city_lv;

    private LetterListView total_city_letters_lv;

    private TextView area_text;

    private SchoolListAdapter schoolListAdapter;

    /**
     * 获取到的学校集合
     */
    private List<SchoolDetails> mSchoolDetails = new ArrayList<>();

    private RelativeLayout address_layout;

    /**
     * 地区名
     */
    private String mAreaStr;

    /**
     * mSchoolArea :地区码
     * mKeyWords:搜索关键字
     */
    private String mSchoolArea, mKeyWords, brandId;
    private ImageView choose_school_go_back;

    private boolean mReady = false;
    private boolean isScroll = false;

    /**
     * 地区选择容器
     */
    private WheelChooser mChooseCityContainer;

    // 存放存在的汉语拼音首字母和与之对应的列表位置
    private Map<String, Integer> alphaIndexer = new HashMap<>();

    //所有学校的拼音首字母集合
    private List<String> pinYinList = new ArrayList<>();

    private int mPageIndex = 1;
    private int mPageSize = 50;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏标题栏
        hideTitleBar();
        // 默认软键盘不弹出
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }

    @Override
    protected int setView() {
        return R.layout.activity_area_school;
    }

    @Override
    protected void findViews() {
        // mChooseCityContainer = new WheelChooser(this);
        search_school_layout = findViewById(R.id.search_school_layout);
        edt_searching_book_str = findViewById(R.id.edt_searching_book_str);
        iv_clear_keywords = findViewById(R.id.iv_clear_keywords);
        school_name_text = findViewById(R.id.school_name_text);
        update_school_text = findViewById(R.id.update_school_text);
        total_city_lv = findViewById(R.id.total_city_lv);
        total_city_letters_lv = findViewById(R.id.total_city_letters_lv);
        choose_school_go_back = findViewById(R.id.choose_school_go_back);
        address_layout = findViewById(R.id.address_layout);
        area_text = findViewById(R.id.area_text);
        setChooseCity();

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.update_school_text) {
            if (null != mChooseCityContainer) {
                mChooseCityContainer.showWheel();
            }
        } else if (id == R.id.choose_school_go_back) {
            finish();
        }else if (id == R.id.search_school_layout || id == R.id.edt_searching_book_str
        || id == R.id.iv_clear_keywords){
            MeJumpManager.jumpToSearchSchool(R.string.go_back,mSchoolArea,mAreaStr,ChooseCitySchoolActivity.this, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_SEARCH_SCHOOL);
        }
    }

    private class LetterListViewListener implements
            LetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            isScroll = false;
            if (null != alphaIndexer) {
                if (alphaIndexer.get(s) != null) {
                    int position = alphaIndexer.get(s);
                    total_city_lv.setSelection(position);
                }
            }
        }
    }

    @Override
    protected void initEvent() {
        update_school_text.setOnClickListener(this);
        iv_clear_keywords.setOnClickListener(this);
        choose_school_go_back.setOnClickListener(this);
        edt_searching_book_str.setOnClickListener(this);
        iv_clear_keywords.setOnClickListener(this);
        total_city_lv.setPullLoadEnable(true);
        total_city_lv.setPullRefreshEnable(false);
        total_city_lv.setPullRefreshListener(this);
        search_school_layout.setOnClickListener(this);
        total_city_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SchoolDetails schoolDetails = (SchoolDetails) adapterView.getItemAtPosition(i);
                CWSys.setSharedString(BaseConstants.SHARE_KEY_SCHOOL_AREA,mSchoolArea);
                CWSys.setSharedString(BaseConstants.SHARE_KEY_AREA_STR,mAreaStr);
                returnSchool(schoolDetails);

            }
        });
        //设置edittext不可编辑
        edt_searching_book_str.setFocusable(false);

        /*edt_searching_book_str.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //Toast.LENGTH_LONG表示显示时间长  Toast.LENGTH_SHORT表示显示时间短
                String text = edt_searching_book_str.getText().toString().trim();
                if (TextUtils.isEmpty(text)) {
//            CWToast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT, true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
                    return true;
                }
                mKeyWords = text;
                try {
                    mKeyWords = java.net.URLEncoder.encode(mKeyWords, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    mKeyWords = "";
                }
               // mKeyWords = text;
                showCricleProgress();
                mPageIndex = 1;
                getSchoolList("", "", mKeyWords);

                //隐藏软键盘
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                return true;
            }
        });*/

    }

    @Override
    protected void init() {
        brandId = EApplication.BRAND_ID + "";
        schoolListAdapter = new SchoolListAdapter(this, mSchoolDetails, alphaIndexer);
        total_city_lv.setAdapter(schoolListAdapter);
        total_city_lv.setOnScrollListener(this);
        total_city_letters_lv.setOnTouchingLetterChangedListener(new LetterListViewListener());
    }

    //初始化地区选择器
    public void setChooseCity() {
        mSchoolArea = CWSys.getSharedString(BaseConstants.SHARE_KEY_SCHOOL_AREA,"440306");
        mAreaStr = CWSys.getSharedString(BaseConstants.SHARE_KEY_AREA_STR);
        if (null != mAreaStr && !"".equals(mAreaStr)){
            school_name_text.setText(mAreaStr);
        }
        mChooseCityContainer = new WheelChooser(ChooseCitySchoolActivity.this);
        mChooseCityContainer.setCallback(new MChosseCityCallBack());
        if (mSchoolArea != null) {
            mChooseCityContainer.setCurrentCity(mSchoolArea);
        }
    }

    @Override
    protected void loadData() {
        mPageIndex = 1;
        showCricleProgress();
        getSchoolList(mSchoolArea, null, mKeyWords);
    }

    /**
     * 查找学校列表 不需要登录
     * @param schoolArea 地区码
     * @param period 	学校学段
     * @param keyWords 搜索关键字
     */
    public void getSchoolList(String schoolArea, String period, final String keyWords) {
        EpaperDao.getInstance().getSchoolList(schoolArea, period, keyWords, brandId, mPageIndex, mPageSize, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                //super.failed(errorCode,data);
                hideCricleProgress();
                total_city_lv.stopLoadMore();


            }

            @Override
            public void failed(Object data) {
                //super.failed(data);
                hideCricleProgress();
                total_city_lv.stopLoadMore();
            }

            @Override
            public void success(Object data) {
                super.success(data);
                hideCricleProgress();
                if (null != data) {
                    SchoolPageBean schoolPageBean = (SchoolPageBean) data;
                    if (mPageIndex == 1) {
                        if (null != schoolPageBean.getPageList()) {
                            mSchoolDetails = schoolPageBean.getPageList();
                            //获取学校拼音首字母
                            getSchoolPinYin();
                            //根据拼音首字母排序
                            sort();
                            //设置学校所在城市
                            if (null != keyWords && !"".equals(keyWords)){
                                school_name_text.setText("");
                                //setCity();
                            }
                            schoolListAdapter.setData(mSchoolDetails);
                            if (null != total_city_letters_lv) {
                                total_city_letters_lv.setNewData(pinYinList);
                            }
                        }
                    } else {
                        if (null != schoolPageBean.getPageList() && schoolPageBean.getPageList().size() > 0) {
                            total_city_lv.stopLoadMore();
                            mSchoolDetails.addAll(schoolPageBean.getPageList());
                            //获取学校拼音首字母
                            getSchoolPinYin();
                            //根据拼音首字母排序
                            sort();
                            //设置学校所在城市
                            if (null != keyWords && !"".equals(keyWords)){
                                school_name_text.setText("");
                                //setCity();
                            }
                            schoolListAdapter.setData(mSchoolDetails);
                            if (null != total_city_letters_lv) {
                                total_city_letters_lv.setNewData(pinYinList);
                            }
                        } else {
                            total_city_lv.stopLoadMore(true);
                        }
                    }
                }
                mKeyWords = null;
            }
        });
    }

    /**
     * 搜索时获取学校所在城市
     */
    private void setCity(){
        for (int i = 0; i < mSchoolDetails.size(); i++) {
            String address = Utils.getAddress(this, mSchoolDetails.get(i).getSchoolArea(), "-");
            mSchoolDetails.get(i).setZoneStr(address);
        }

    }

    /*
     根据拼音排序
     */
    public void sort() {

        // 获取中文环境
        final Comparator comparator = Collator.getInstance(Locale.CHINA);
        // 排序实现
        Collections.sort(mSchoolDetails, new Comparator<SchoolDetails>() {
            @Override
            public int compare(SchoolDetails o1, SchoolDetails o2) {
                return comparator.compare(o1.getSchoolName(), o2.getSchoolName());
            }
        });

        // 排序实现
        Collections.sort(pinYinList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return comparator.compare(o1, o2);
            }
        });
    }

    /**
     * 获取学校首字母拼音
     */
    public void getSchoolPinYin() {
        try {
            pinYinList.clear();
            for (int i = 0; i < mSchoolDetails.size(); i++) {
                String pinyin = getPinyin(mSchoolDetails.get(i).getSchoolName());
                mSchoolDetails.get(i).setKey(pinyin);
                pinYinList.add(pinyin);
            }
            //去除重复首字母
            if (pinYinList.size() > 0) {
                Set<String> set = new HashSet<>();
                set.addAll(pinYinList);
                pinYinList.clear();
                pinYinList.addAll(set);
            }
            //total_city_letters_lv = new LetterListView(this);
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        mPageIndex++;
        showCricleProgress();
        String text = edt_searching_book_str.getText().toString().trim();
        if (!TextUtils.isEmpty(text)) {
          mKeyWords = text;
        try {
            mKeyWords = java.net.URLEncoder.encode(mKeyWords, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            mKeyWords = "";
        }
        //CWToast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT, true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
        }
        getSchoolList(mSchoolArea, null, mKeyWords);
    }

    /**
     * 获取汉字拼音首字母
     *
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public String getPinyin(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        // 设置大小写格式
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        // 设置声调格式：
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //匹配中文,非中文转换会转换成null
        if (charArray.length > 0) {
            if (Character.toString(charArray[0]).matches("[\\u4E00-\\u9FA5]+")) {
                String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(charArray[0], defaultFormat);
                if (hanyuPinyinStringArray != null) {
                    pinyin.append(hanyuPinyinStringArray[0].charAt(0));
                }
            }
        }

        return pinyin.toString();
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {

    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {

    }


    /**
     * 内部类,处理,地区选择监听器事件
     */
    class MChosseCityCallBack extends WheelChooser.ChooseCityCallback {
        @Override
        public void choosen(City choosenCity, String areaStr) {
            mChooseCityContainer.hideWheel();
            mAreaStr = areaStr;
            school_name_text.setText(areaStr);
            mSchoolArea = choosenCity.getZoneNum() + "";
            mPageIndex = 1;
            showCricleProgress();
            getSchoolList(mSchoolArea, null, mKeyWords);

        }

        @Override
        public void initCity(City choosenCity, String areaStr) {
            //mAddressTv.setText(areaStr);
        }

        @Override
        public void cancel() {
            mChooseCityContainer.hideWheel();
        }
    }

    public String getSchoolArea(String areaStr) {
        String area = "";
        if (null != areaStr) {
            String[] s = areaStr.split(" ");
            area = s[s.length - 1];
        }
        return area;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_SEARCH_SCHOOL:
                    if (null != data) {
                        SchoolDetails schoolData =(SchoolDetails) data.getSerializableExtra(IntentFlag.INTENT_FLAG_SCHOOL_DATA);
                        returnSchool(schoolData);
                    }
            }
        }
    }

    /**
     * 返回选择的学校信息
     * @param schoolDetails
     */
    public void returnSchool(SchoolDetails schoolDetails) {
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_SCHOOL_ID, schoolDetails.getSchoolId());
        intent.putExtra(IntentFlag.INTENT_FLAG_SCHOOL_NAME, schoolDetails.getSchoolName());
        setResult(RESULT_OK, intent);
        finish();
    }
}
